const http = require('http');
const fs = require('fs');
const path = require('path');

let mime =
    {
        html: 'text/html',
        css: 'text/css',
        js: 'text/javascript',
        png: 'image/png',
        jpg: 'image/jpeg',
        gif: 'image/gif',
        mp4: 'video/mp4',
        mp3: 'audio/mpeg',
        json: 'application/json'
    };
const server = http.createServer((request,response) => {
    if (request.method !== 'GET') {
        response.statusCode = 405;
        response.end('<h1>405 Method is not allowed</h1>');
        return;
    }
    //获得路径
    let {pathname} = new URL(request.url,'http://localhost:9000');
    //每次写这写if else 不好
    let filePath = __dirname + pathname;  //直接拼接
    //用异步的读取
    fs.readFile(filePath,(err,data) => {
        if (err) {
            //错误处理解决
            switch (err.code) {
                case 'ENOENT':
                    response.statusCode = 404;
                    response.end('<h1>404 Not Found</h1>');
                    return;
                case 'EPERM':
                    response.statusCode = 403;
                    response.end('<h1>403 没有权限</h1>');
                    return;
            }
            console.log(err);

        }
        response.end(data);
    });
    //获得网页的后缀名
    let ext = path.extname(filePath).slice(1);
    // console.log(ext);
    //获取mime类型
    let type = mime[ext];
    // console.log(type);
    //设置网页的，mime类型
    if (type) {//解决乱码问题
        //处理方案 html的资源处理为utf-8 其他资源不做处理
        if (ext === 'html') {
            response.setHeader('content-type',type + ';charset=utf-8');
        } else {
            response.setHeader('content-type',type);
        }

    } else {
        response.setHeader('content-type','application/octet-stream');
    }
});

server.listen(9000,() => {
    console.log('服务已经启动 9000端口已经启动....')
});